﻿using Microsoft.Extensions.Configuration;
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;


namespace Inventorycount.Infrastructure
{
    public class DapperHeler<T>
    {
        public readonly string _connectionString;
        public DapperHeler(IConfiguration configration)
        {
            _connectionString = configration.GetConnectionString("str");
        }
        //创建并打开数据库连接
        public IDbConnection GetConnection()
        {
            var connection = new SqlConnection(_connectionString);
            connection.Open();
            return connection;
        }
        //返回单个对象
        public T? GetTable(string sql)
        {
            using (var connection = GetConnection())
            {
                //使用Dapper执行
                var result = connection.QueryFirstOrDefault<T>(sql);
                Console.WriteLine($"执行的sql语句:{sql}");
                connection.Close();
                return result;
            }
        }
        //返回一个集合
        public List<T> GetT_StudList(string sql)
        {
            using (var connection = GetConnection())
            {
                var invoices = connection.Query<T>(sql).ToList();
                Console.WriteLine($"执行的sql语句:{sql}");
                connection.Close();
                return invoices;
            }
        }



        public async Task<object> ExecuteScalar(string sql)
        {
            using (var connection = GetConnection())
            {
                var num = await connection.ExecuteScalarAsync(sql);
                connection.Close();
                return num;
            }
        }
    }
}
